package com.skt.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RateLimitUtil {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 检查IP注册频率限制
     */
    public void checkRegisterRateLimit(String ip) {
        String ipKey = "register_rate:ip:" + ip;
        Long ipCount = redisTemplate.opsForValue().increment(ipKey, 1);
        
        if (ipCount != null && ipCount == 1) {
            // 第一次设置过期时间（1小时）
            redisTemplate.expire(ipKey, 1, TimeUnit.HOURS);
        }
        
        if (ipCount > 5) {
            throw new RuntimeException("注册频率过高，请1小时后再试");
        }
    }

    /**
     * 检查设备注册频率限制
     */
    public void checkDeviceRegisterLimit(String deviceId) {
        String deviceKey = "register_rate:device:" + deviceId;
        Long deviceCount = redisTemplate.opsForValue().increment(deviceKey, 1);
        
        if (deviceCount != null && deviceCount == 1) {
            // 第一次设置过期时间（24小时）
            redisTemplate.expire(deviceKey, 24, TimeUnit.HOURS);
        }
        
        if (deviceCount > 3) {
            throw new RuntimeException("该设备注册次数已达上限");
        }
    }

    /**
     * 检查登录频率限制
     */
    public void checkLoginRateLimit(String username) {
        String loginKey = "login_rate:" + username;
        Long loginCount = redisTemplate.opsForValue().increment(loginKey, 1);
        
        if (loginCount != null && loginCount == 1) {
            // 5分钟内限制
            redisTemplate.expire(loginKey, 5, TimeUnit.MINUTES);
        }
        
        if (loginCount > 5) {
            throw new RuntimeException("登录尝试次数过多，请5分钟后再试");
        }
    }

    /**
     * 清除登录失败计数
     */
    public void clearLoginRateLimit(String username) {
        String loginKey = "login_rate:" + username;
        redisTemplate.delete(loginKey);
    }
}